<template>
	<div class="new-component">
		<el-table ref="table" v-loading="listLoading" v-el-table-infinite-scroll="load" class="virtual-table" :data="virtualRows"
		 :height="440" :max-height="440" :row-key="getRowKeys" @select-all="handleSelectionAll" :summary-method="getSummaries"
		 show-summary >
			<el-table-column type="selection" :reserve-selection="true" width="100" />
			<el-table-column prop="date" label="日期" min-width="180px" />
			<el-table-column prop="name" label="姓名" min-width="180px" />
			<el-table-column prop="address" label="地址" min-width="180px" />
		</el-table>
	</div>
</template>

<script>
	import elTableInfiniteScroll from 'el-table-infinite-scroll';
	import {
		debounce,
		throttle
	} from 'throttle-debounce';
	export default {
		directives: {
			'el-table-infinite-scroll': elTableInfiniteScroll
		},
		data() {

			return {
				tableData: [],
				virtualRows: [],
				listLoading: false,
				selectedAllStatus: false,
				selectedRow: [],
				selectedRowIds: []
			}
		},
		created() {
			for (let i = 0; i < 100; i++) {
				this.tableData.push({
					id: i,
					date: i,
					name: 'i' + i,
					address: i + '-' + i + '-' + i + '-' + i
				})
			}
			this.throttleResize = debounce(10, () => {
				this.handleScroll()
			})
		},
		beforeMount() {},
		mounted() {
			this.addListeners()
			this.updateVisibleItems()
		},
		beforeDestroy() {
			this.removeListeners()
		},
		methods: {
			// 对table增加监听事件
			addListeners() {
				if (!this.$refs.table.bodyWrapper) {
					return
				}
				this.$refs.table.bodyWrapper.addEventListener('scroll', this.throttleResize)
			},
			removeListeners() {
				if (!this.$refs.table.bodyWrapper) {
					return
				}
				this.$refs.table.bodyWrapper.removeEventListener('scroll', this.throttleResize)
			},
			handleScroll() {
				// console.count('处理滚动事件')
				this.updateVisibleItems()
			},
			updateVisibleItems() {
				const itemSize = 40 // td高度
				const count = this.tableData.length // table总条数
				const bufferCount = 30 // table每次实际渲染条数
				const height = count * itemSize

				// 获取当前滚动条位置
				const scroll = this.getScroll()
				const scrollTop = scroll.start

				// Fixed size mode
				let startIndex
				startIndex = ~~(scrollTop / itemSize)
				startIndex < 0 && (startIndex = 0)
				// startIndex=startIndex<20?0:startIndex-10;
				// 分隔数组
				this.virtualRows = this.tableData.slice(startIndex, startIndex + bufferCount)

				// 设置el-table上的虚拟列表，采用了padding的方案，原因是transform 会使el-table的样式混乱
				const mainTable = this.$refs.table.$el.getElementsByClassName('el-table__body')
				Array.from(mainTable).forEach(table => {
					table.style.height = height + 'px'
					if (startIndex + bufferCount >= count) {
						// 由于el-table 在滚动到最后时，会出现抖动，因此增加判断，单独设置属性
						table.style.paddingTop = scrollTop - itemSize + 'px'
						table.style.paddingBottom = 0
					} else {
						table.style.paddingTop = scrollTop + 'px'
						table.style.paddingBottom = height - scrollTop - bufferCount * itemSize + 'px'
					}
				})

				// 切换选中状态
			},
			getScroll() {
				if (!this.$refs.table.bodyWrapper) {
					return {
						start: 0,
						end: 400
					}
				}
				const dom = this.$refs.table.bodyWrapper
				const scrollState = {
					start: dom.scrollTop,
					end: dom.scrollTop + dom.clientHeight
				}
				return scrollState
			},
			handleSelectionAll(selection) {
				this.selectedAllStatus = !this.selectedAllStatus
				const refsElTable = this.$refs.table // 获取表格对象
				const tableDataLength = this.tableData.length
				if (this.selectedAllStatus) {
					console.log('选中所有行')
					refsElTable.clearSelection() // 先清空
					for (let index = 0; index < tableDataLength; index++) {
						// 选中所有行
						refsElTable.toggleRowSelection(this.tableData[index], true)
					}
				} else {
					console.log('清空选中所有行')
					refsElTable.clearSelection()
				}
			},
			getRowKeys(row) {
				return row.id // 设定每一条对应一个key
			},
			load(){
				var throttleFun =throttle(500, () => {
					console.log(this)
					if (this.tableData.length > 10000) {
						this.$message.info("已经到底了");
						return;
					}
					if(this.listLoading){
						return
					}
					this.listLoading = true;
					setTimeout(()=>{
						this.$message.success('加载下一页');
						const exampleData = new Array(1000).fill().map((v, i) => {
							return {
								id: this.tableData.length + i,
								date: this.tableData.length + i,
								name: '王小虎',
								province: '上海',
								city: '普陀区',
								address: '上海市普陀区金沙江路 1518 弄',
								zip: 200333
							}
						});
						this.listLoading = false;
						this.tableData = this.tableData.concat(exampleData);
						console.log(this.tableData)
						this.updateVisibleItems()
					},1000)
					
				})
				throttleFun()
			},
			// arraySpanMethod({row,column,rowIndex,columnIndex}) {
			// if (rowIndex % 2 === 0) {
			// 	if (columnIndex === 0) {
			// 		return [1,4];
			// 	} else if (columnIndex === 1) {
			// 		return [0, 0];
			// 	}
			// }
			// if(rowIndex==0){
			// 	return [0,4];
			// }
			// },
			getSummaries(param) {
				// console.log(param)
				const {
					columns,
					data
				} = param;
				const sums = [];
				columns.forEach((column, index) => {
					if (index === 0) {
						sums[index] = '总价';
						return;
					}
					const values = data.map(item => Number(item[column.property]));
					if (!values.every(value => isNaN(value))) {
						sums[index] = values.reduce((prev, curr) => {
							const value = Number(curr);
							if (!isNaN(value)) {
								return prev + curr;
							} else {
								return prev;
							}
						}, 0);
						sums[index] = '100元';
					} else {
						sums[index] = 'N/A';
					}
				});

				return sums;
			}
		}
	}
</script>

<style scoped>
	::v-deep.el-table th {
		background: #f4f4f4 !important;
		height: 40px !important;
		padding: 0 0 !important;
	}

	::v-deep.el-table td {
		height: 40px !important;
		padding: 0 0 !important;
	}

	.el-table::before {
		display: none;
	}
</style>
